package secondweek.four;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * Created by zhourui on 2016/8/17.
 */
public class CountTask extends RecursiveTask<List<SalaryTeam>> {
    private List<String> salaries;
    private int start;
    private int end;
    public CountTask(int start,int end, List<String> salaries) {
        this.salaries = salaries;
        this.start = start;
        this.end = end;
    }

    @Override
    protected List<SalaryTeam> compute() {
        List<SalaryTeam> salaryTeamList  = new ArrayList<>();
        boolean canCompute = (end - start) <= 10;

        if (canCompute){
            int from = start;
            for (int i = start; i < end; i++){
                if(!compareFirstTwoWords(salaries.get(i),salaries.get(i+1))){
                    SalaryTeam salaryTeam = new SalaryTeam(from,i,calFromToTotal(from,i,salaries));
                    salaryTeamList.add(salaryTeam);
                    from = i+1;
                }
            }
            //添加最后一个
            SalaryTeam salaryTeam = new SalaryTeam(from,end,calFromToTotal(from,end,salaries));
            salaryTeamList.add(salaryTeam);
        }else{
            int middle = (start + end) / 2;
            CountTask leftCountTask = new CountTask(start, middle, salaries);
            CountTask rightCountTask = new CountTask(middle+1, end, salaries);
            leftCountTask.fork();
            rightCountTask.fork();
            List<SalaryTeam> leftResult = leftCountTask.join();
            List<SalaryTeam> rightResult = rightCountTask.join();

            //左右合并
            if (compareFirstTwoWords(salaries.get(leftResult.get(leftResult.size()-1).getFrom()),
                    salaries.get(rightResult.get(0).getFrom()))){
                int total = leftResult.get(leftResult.size()-1).getTotal()+
                                rightResult.get(0).getTotal();
                leftResult.get(leftResult.size()-1).setTo(rightResult.get(0).getTo());
                leftResult.get(leftResult.size()-1).setTotal(total);
            }
            rightResult.remove(0);
            salaryTeamList.addAll(leftResult);
            salaryTeamList.addAll(rightResult);
        }
        return salaryTeamList;
    }

    private boolean compareFirstTwoWords(String salary0, String salary1){
        if (salary0.charAt(0) == salary1.charAt(0)
                && salary0.charAt(1) == salary1.charAt(1)){
            return true;
        }
        return false;
    }

    private int calFromToTotal(int from,int to,List<String> salaries){
        int total = 0;
        for (int i = from; i <= to; i++){
            String[] salaryArray = salaries.get(i).split(",");
            total += Integer.parseInt(salaryArray[1]) * 12 + Integer.parseInt(salaryArray[2]);
        }
        return total;
    }
}
